package com.eye.system.service.impl;


import com.eye.common.utils.SecurityUtils;
import com.eye.system.domain.Device;
import com.eye.system.exception.DMPException;
import com.eye.system.mapper.DeviceMapper;
import com.eye.system.search.DeviceSearch;
import com.eye.system.service.DeviceService;
import com.eye.system.util.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service("deviceService")
public class DeviceServiceImpl implements DeviceService {

    @Resource
    private DeviceMapper deviceMapper;

    @Override
    public Integer addDevice(Device device) {
        if (device != null) {
            device.setCreateDate(CommonUtil.getSystemTime(CommonUtil.FORMAT_STR_SECOND));
            device.setCreateBy(SecurityUtils.getUsername());
            device.setState(2);
            int add = deviceMapper.insert(device);
            if (add > 0) {
                return add;
            }
            throw new DMPException("添加设备失败");
        }
        throw new DMPException("无效参数");
    }

    @Override
    public Integer deleteDevice(Integer id) {
        int delete = deviceMapper.deleteById(id);
        if (delete > 0) {
            return delete;
        }
        throw new DMPException("删除设备失败");
    }

    @Override
    public Integer updateDevice(Integer id,Device device) {
        Device d = deviceMapper.selectById(id);
        if (d == null) {
            throw new DMPException("该设备不存在");
        }
        device.setUpdateDate(CommonUtil.getSystemTime(CommonUtil.FORMAT_STR_SECOND));
        device.setUpdateBy(SecurityUtils.getUsername());
        Integer update = deviceMapper.updateByIdSelective(device);
        if (update > 0) {
            return update;
        }
        throw new DMPException("修改设备失败");
    }

    @Override
    public Device selectById(Integer id) {
        Device device = deviceMapper.selectById(id);
        if (device != null) {
            return device;
        }
        throw new DMPException("该设备不存在");
    }

    @Override
    public PageResult selectPaging(DeviceSearch deviceSearch) {
        PageRequest pageRequest = new PageRequest();
        return PageUtils.getPageResult(pageRequest, getPageInfo(deviceSearch));
    }

    private PageInfo<Device> getPageInfo(DeviceSearch deviceSearch) {
        PageHelper.startPage(deviceSearch.getPageNum(), deviceSearch.getPageSize());
        List<Device> deviceList = deviceMapper.select(deviceSearch);
        return new PageInfo<Device>(deviceList);
    }

    @Override
    public Integer activation(Integer id) {
        Device device = deviceMapper.selectById(id);
        device.setState(1);
        Integer update = deviceMapper.updateByIdSelective(device);
        if (update > 0) {
            return device.getState();
        }
        throw new DMPException("激活失败");
    }
}
